/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-11-07 12:14:27
 * @LastEditTime : 2024-02-18 18:23:43
 */
import { Body, Headers, Inject, Post } from '@midwayjs/decorator';
import { CoolController, BaseController, RESCODE } from '@cool-midway/core';
import axios from 'axios';
import * as request from 'request';

/**
 * 代理
 */
@CoolController()
export class ProxyController extends BaseController {
  @Post('/')
  async proxy(@Body() body) {
    // 或者如果你想要修改全局默认配置
    axios.defaults.xsrfCookieName = undefined;
    axios.defaults.xsrfHeaderName = undefined;

    // 如果你正在处理withCredentials，也可以将其设置为false以避免发送cookies（包括可能用于XSRF防护的cookie）
    axios.defaults.withCredentials = false;
    const { headers } = this.baseCtx;
    try {
      const proxyBody = {
        ...body,
      };
      delete proxyBody.ik_datav_proxy_api;
      delete proxyBody.ik_datav_proxy_method;
      const config = {
        method: body.ik_datav_proxy_method,
        url: body.ik_datav_proxy_api,
        headers: {
          ...headers,
          'User-Agent': 'Iking_Datav/1.0.0',
          'Content-Type': 'application/json',
          Accept: '*/*',
          Connection: 'keep-alive',
        },
        data: JSON.stringify(proxyBody || {}),
      };
      const response = await axios(config);
      return response.data;
    } catch (error) {
      return this.ok({
        code: RESCODE.COMMFAIL,
        message: error?.message || '请求错误',
      });
    }
  }
}
